<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button v-allow="'import'" type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button v-allow="'export_excel'" type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button v-allow="'add'" type="primary" size="small" @click="hAdd">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table
          border
          :data="list"
          :default-sort="{prop: 'timeOfEntry', order: 'ascending'}"
        >
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" prop="username">
            <template #default="{row}">
              <img :src="row.staffPhoto" alt="" style="width:100px;height:100px">
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{ getFormOfEmployment(row.formOfEmployment) }}
            </template>
          </el-table-column>

          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail?id=${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="assignRoles(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[2, 5, 10, 15]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>

    </div>
    <el-dialog
      title="提示"
      :visible.sync="showDialog"
      @close="close"
    >
      <addorEdit ref="refForm" @success="hSuccess" @close="hClose" />
    </el-dialog>

    <!-- 分配角色的显示与隐藏 -->
    <el-dialog
      title="提示"
      :visible.sync="showRoleDialog"
    >
      <assignRole v-if="showRoleDialog" :role-id="roleId" @close="showRoleDialog = false" />
    </el-dialog>
  </div>
</template>

<script>
import assignRole from './assignRole.vue'
import { getEmployeeList, delEmployee } from '@/api/modules/employees'
import EmployeeEnum from '@/constant/employees'
import addorEdit from './empDialog'
// console.log(EmployeeEnum.hireType)
const hireType = {}
EmployeeEnum.hireType.forEach(item => { hireType[item.id] = item.value })
export default {
  components: { addorEdit, assignRole },
  data() {
    return {
      roleId: '', // 分配角色时的id
      showRoleDialog: false, // 控制分配角色的弹框的显示与隐藏
      showDialog: false, // 控制弹框的显示与隐藏
      total: 0, // 员工列表的总数
      list: [], // 员工的列表
      page: 1,
      size: 2
    }
  },
  created() {
    this.loadEmployeeList()
  },

  methods: {
    assignRoles(id) {
      this.showRoleDialog = true
      this.roleId = id
    },
    // Excel导出
    // 封装函数
    Dateformat(list) {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }

      const one = list[0]
      let headers = []
      if (one) {
        console.log(' Object.keys(one)', Object.keys(one))
        headers = Object.keys(one).map(item => {
          return mapInfo[item]
        })
      }
      const data = list.map(item => {
        return Object.values(item)
      })
      return { headers, data }
    },
    // 导出时的请求
    async handleDownload() {
      const res = await getEmployeeList(this.page, this.size)
      console.log(res.data.rows)
      const { headers, data } = this.Dateformat(res.data.rows)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          // header: ['姓名', '工资'], // 表头 必填
          header: headers, // 表头 必填
          data,
          // data: [
          //   ['刘备11111111111111', 100],
          //   ['关羽', 500]
          // ], // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    close() {
      this.$refs.refForm.resetForm()
    },
    hClose() {
      this.showDialog = false
    },
    // 成功之后的操作
    hSuccess() {
      this.showDialog = false
      this.total++
      const maxPage = Math.ceil(this.total / this.size)
      this.page = maxPage
      this.loadEmployeeList()
    },
    // 新增内容
    hAdd() {
      this.showDialog = true
    },
    // 删除内容
    async hDel(id) {
      try {
        const res = await delEmployee(id)
        console.log('delEmployee', res)
        if (this.list.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
        this.loadEmployeeList()
        // 保存数据
      } catch (err) {
        console.log('delEmployee', err)
      }
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.page = 1
      this.size = val
      this.loadEmployeeList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployeeList()
    },
    // 聘用形式的格式转换
    getFormOfEmployment(value) {
      return hireType[value] || '未知'
    },
    // 获取员工的列表
    async loadEmployeeList() {
      try {
        const res = await getEmployeeList(this.page, this.size)
        // console.log('getEmployeeList', res)
        this.list = res.data.rows
        this.total = res.data.total
        // 保存数据
      } catch (err) {
        console.log('getEmployeeList', err)
      }
    }
  }
}
</script>
